<script setup lang="ts">
import Envs from "@/components/Envs.vue";
import HostSelect from "@/components/HostSelect.vue";
import type { Crontab, Forward } from "@/stores/master/types";
import { getBy, getIndexBy } from "@/utils/array";
import { setup } from "@/utils/setup.js";
import { AutorenewFilled } from "@vicons/material";
import { deepClone } from "fast-json-patch";
import {
  NButton,
  NCard,
  NDynamicInput,
  NForm,
  NFormItem,
  NIcon,
  NInput,
  NInputGroup,
  NInputGroupLabel,
  NInputNumber,
  NSelect,
  NSpace,
} from "naive-ui";
import { v4 as uuidv4 } from "uuid";
import { ref, watchEffect } from "vue";

const { configStore, route, router } = setup();

const forward = ref<Forward>();

function createForward(): Forward {
  return {
    id: uuidv4(),
    from: { type: "custom", host: "", custom: { ip: "", port: 0 } },
    to: { host: "", port: 0 },
  };
}

function saveHost() {
  // TODO 验证表单数据
  const index = getIndexBy(
    configStore.config!.forwards,
    "id",
    forward.value!.id
  );
  if (index !== -1) {
    configStore.config!.forwards[index] = forward.value!;
  } else {
    configStore.config!.forwards.push(forward.value!);
  }
  router.push({ name: "hosts" });
}

watchEffect(() => {
  const id = route.query["id"] as string | undefined;
  if (id !== undefined) {
    if (configStore.config !== undefined) {
      const value = getBy(configStore.config.forwards, "id", id);
      if (value !== undefined) {
        forward.value = deepClone(value);
      }
    }
  } else {
    forward.value = createForward();
  }
});
</script>

<template>
  <NForm
    style="padding: 16px 32px 16px 16px"
    label-placement="left"
    label-width="auto"
  >
    <NFormItem label="唯一标识">
      <NInput v-if="forward === undefined" disabled />
      <NInput v-else v-model:value="forward.id" />
    </NFormItem>
    <NFormItem label="源主机">
      <NSelect v-if="forward === undefined" disabled />
      <HostSelect v-else v-model:value="forward.from.host" />
    </NFormItem>
    <template v-if="forward?.from.type !== 'custom'">
      
    </template>
    <NFormItem label="源端口">
      <NInput v-if="forward?.from.type !== 'custom'" disabled />

      <HostSelect v-else v-model:value="forward.from" />
    </NFormItem>
    <NFormItem label="目标主机">
      <NSelect v-if="forward === undefined" disabled />
      <HostSelect v-else v-model:value="forward.to.host" />
    </NFormItem>
    <NFormItem>
      <NButton
        style="margin-left: auto"
        attr-type="button"
        :disabled="forward === undefined"
        @click="saveHost"
      >
        保存
      </NButton>
    </NFormItem>
  </NForm>
</template>
